package com.beautiful.xin.sort;

import java.util.Arrays;
import java.util.concurrent.CompletableFuture;

public class QuickSort {
    public static void main(String[] args) {
        int[] arr2 = {7, 2, 6, 5, 9, 11, 13, 31, 14};
        quickSort1(arr2, 0, arr2.length - 1);
//        tk(arr2, 0, arr2.length - 1,4);

        System.out.println(Arrays.toString(arr2));

        int[] aar = {3,2,3,1,2,4,5,5,6};
        //fk(aar, 0, aar.length - 1, 6);
        quickSort1(aar,0,aar.length-1);
        System.out.println(Arrays.toString(aar));
    }

    public static void fk(int[] arr, int left, int right, int k) {
        if (left < right) {
            int l = left;
            int r = right;
            int mv = arr[l];
            while (l < r) {
                while (l < r && arr[r] <= mv) r--;
                arr[l] = arr[r];
                while (l < r && arr[l] >= mv) l++;
                arr[r] = arr[l];
            }
            arr[l] = mv;
            if (l == k-1) return;
            if (l < k-1) fk(arr, l + 1, right, k);
            if (l > k-1) fk(arr, left, r - 1, k);
        }
    }

    public static void quickSort1(int[] arr, int left, int right) {
        if (left < right) {
            int l = left;
            int r = right;
            int midval = arr[l];
            while (l < r) {
                while (l < r && arr[r] >= midval) {
                    r--;
                }
                arr[l] = arr[r];
                while (l < r && arr[l] <= midval) {
                    l++;
                }
                arr[r] = arr[l];
            }
            arr[r] = midval;
            quickSort1(arr, left, r - 1);
            quickSort1(arr, l + 1, right);
        }
    }

    public static void tk(int[] arr, int left, int right, int k) {
        if (left < right) {
            int l = left;
            int r = right;
            int midval = arr[l];
            while (l < r) {
                while (l < r && arr[r] < midval) r--;
                arr[l] = arr[r];
                while (l < r && arr[l] > midval) l++;
                arr[r] = arr[l];
            }
            arr[l] = midval;
            if (l == k) return;
            if (l < k) tk(arr, l + 1, right, k);
            if (l > k) tk(arr, left, r - 1, k);
        }
    }

}





















